package com.pzhu.controller;

/**
 * @Author : zqh
 * @Date : 2023/11/27 0027 下午 7:02
 * @Version: 1.0
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzhu.common.constant.Constant;
import com.pzhu.model.entity.Role;
import com.pzhu.model.entity.RoleMenu;
import com.pzhu.model.entity.UserRole;
import com.pzhu.model.help.PageBean;
import com.pzhu.model.help.ResponseResult;
import com.pzhu.service.RoleMenuService;
import com.pzhu.service.RoleService;
import com.pzhu.service.UserRoleService;
import com.pzhu.utils.RedisUtil;
import com.pzhu.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统角色Controller控制器
 */
@RestController
@Api(tags = "系统角色")
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("查询所有的角色")
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResponseResult listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        List<Role> roleList = roleService.list();
        resultMap.put("roleList",roleList);
        return ResponseResult.ok(resultMap);
    }

    /**
     * 根据条件分页查询角色列表
     * @param pageBean
     * @return
     */
    @ApiOperation("根据条件分页查询角色列表")
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResponseResult list(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<Role> pageResult = roleService.page(
                new Page<>(pageBean.getPageNum(),pageBean.getPageSize()),
                new QueryWrapper<Role>().like(StringUtil.isNotEmpty(query), "name", query));
        List<Role> roleList = pageResult.getRecords();
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("roleList",roleList);
        resultMap.put("total",pageResult.getTotal());
        return ResponseResult.ok(resultMap);
    }

    /**
     * 添加或者修改
     * @param role
     * @return
     */
    @ApiOperation("添加或者修改角色信息")
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')"+"||"+"hasAuthority('system:role:edit')")
    public ResponseResult save(@RequestBody @Valid Role role){
        if(role.getId()==null || role.getId()==-1){
            role.setCreateTime(new Date());
            roleService.save(role);
        }else{
            role.setUpdateTime(new Date());
            roleService.updateById(role);
        }
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return ResponseResult.ok();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @ApiOperation("根据id查询角色信息")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    @ApiImplicitParam(name = "id",value = "角色ID",required = true)
    public ResponseResult findById(@PathVariable(value = "id")Long id){
        Role role = roleService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysRole",role);
        return ResponseResult.ok(map);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public ResponseResult delete(@RequestBody Long[] ids){
        roleService.removeByIds(Arrays.asList(ids));
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().in(UserRole::getRoleId,ids));
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return ResponseResult.ok();
    }

    /**
     * 获取当前角色的权限菜单
     * @param id
     * @return
     */
    @ApiOperation("获取当前角色的权限菜单")
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResponseResult menus(@PathVariable(value = "id")Long id){
        List<RoleMenu> roleMenuList = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, id));
        List<Long> menuIdList = roleMenuList
                .stream()
                .map(p -> p.getMenuId())
                .collect(Collectors.toList());
        return ResponseResult.ok().put("menuIdList",menuIdList);
    }

    /**
     * 更新角色权限信息
     * @param id
     * @param menuIds
     * @return
     */
    @ApiOperation("更新角色权限信息")
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:edit')")
    public ResponseResult updateMenus(@PathVariable(value = "id")Long id, @RequestBody Long[] menuIds){
        List<RoleMenu> sysRoleMenuList=new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId->{
            RoleMenu roleMenu=new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(id);
            sysRoleMenuList.add(roleMenu);
        });
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId,id));
        roleMenuService.saveBatch(sysRoleMenuList);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return ResponseResult.ok();
    }
}
